package com.questionnaires.controller;

import com.questionnaires.exception.EmptyListException;
import com.questionnaires.exception.NotExistsException;
import com.questionnaires.model.*;
import com.questionnaires.service.CategoryService;
import com.questionnaires.service.QuestionnaireService;
import com.questionnaires.service.UserResponseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Controller for handling questionnaire operations
 *
 * @author adriana.calina.oros@gmail.com
 */

@Controller
public class QuestionnaireController {

    public static final String ID_QUESTIONNAIRE_SESSION_ATTR = "idQuestionnaire";
    public static final String STATISTICS_QUESTIONNAIRE_VIEW = "public_user/statisticsQuestionnaire";
    @Autowired
    private QuestionnaireService questionnaireService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserResponseService userResponseService;

    /**
     * Add questionnaire view
     */
    private static final String ADD_QUESTIONNAIRE_VIEW = "questionnaire/addQuestionnaire";

    /**
     * All questionnaires view
     */
    private static final String QUESTIONNAIRES_VIEW = "questionnaire/questionnaires";

    private static final String REDIRECT_QUESTIONNAIRE = "redirect:/questionnaires";

    private static final String REDIRECT_ADDQ = "redirect:/addQuestionnaire";

    private static final String REDIRECT_FILL_CREATEDQ = "redirect:/fillCreatedQuestionnaire";

    private static final String QUESTIONNAIRE_NOT_EXISTS = "NotExists.questionnaire";

    //private static final String VIEW_PUBLIC_CATEGORIES = "redirect:/view_questionnaire";

    private static final String VIEW_Q_FROM_CATEGORY = "public_user/view_q_from_category";
    /**
     * Creates questionnaire content view.
     */
    public static final String VIEW_Q_CONTENT = "public_user/get_q_content";

    public QuestionnaireService getQuestionnaireService() {
        return questionnaireService;
    }

    public void setQuestionnaireService(QuestionnaireService questionnaireService) {
        this.questionnaireService = questionnaireService;
    }

    public CategoryService getCategoryService() {
        return categoryService;
    }

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    public UserResponseService getUserResponseService() {
        return userResponseService;
    }

    public void setUserResponseService(UserResponseService userResponseService) {
        this.userResponseService = userResponseService;
    }

    @RequestMapping(value = "/questionnaires", method = RequestMethod.GET)
    public String viewAllQuestionnaires(Map<String, Object> modelMap, HttpSession session) {

        User user = (User)session.getAttribute("user");
        if (user == null || !user.checkUserManager() )
            return UserController.REDIRECT_INDEX;
        try {
            modelMap.put("questionnairesList", questionnaireService.findByManager(user));
        } catch (EmptyListException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return QUESTIONNAIRES_VIEW;
    }


    /**
     * Prepares and retrieves the add questionnaire view
     *
     * @param modelMap the current page model map
     * @return add questionnaire view
     */
    @RequestMapping(value = "/addQuestionnaire", method = RequestMethod.GET)
    public String viewAddQuestionnaire(Map<String, Object> modelMap, HttpSession session) {

        User user = (User)session.getAttribute("user");
        if (user == null || !user.checkUserManager() )
            return UserController.REDIRECT_INDEX;
        modelMap.put("categoryList", categoryService.findAll());
        session.removeAttribute(ID_QUESTIONNAIRE_SESSION_ATTR);
        modelMap.put("questionnaire", new Questionnaire());
        return ADD_QUESTIONNAIRE_VIEW;
    }

    /**
     * Prepares and retrieves the add questionnaire view, for an already created questionnaire,
     * whose id is on the session object.
     *
     * @param modelMap
     * @param session
     * @return
     */
    @RequestMapping(value = "/fillCreatedQuestionnaire", method = RequestMethod.GET)
    public String viewCreatedQuestionnaireToFill(Map<String, Object> modelMap, HttpSession session) {

        User user = (User)session.getAttribute("user");
        if (user == null || !user.checkUserManager() )
            return UserController.REDIRECT_INDEX;
        modelMap.put("categoryList", categoryService.findAll());
        Questionnaire questionnaire;
        Object idObject = session.getAttribute(ID_QUESTIONNAIRE_SESSION_ATTR);
        if (idObject != null) {
            long id = (Long) idObject;
            questionnaire = questionnaireService.findById(id);
        } else {
            questionnaire = new Questionnaire();
        }
        modelMap.put("questionnaire", questionnaire);
        return ADD_QUESTIONNAIRE_VIEW;
    }


    @RequestMapping(value = "/questionnaires/add")
    public String addQuestionnaire(@ModelAttribute("questionnaire")
                                   @Valid Questionnaire questionnaire, BindingResult result,
                                   HttpSession session) {
        User user = (User)session.getAttribute("user");
        if (user == null || !user.checkUserManager() )
            return UserController.REDIRECT_INDEX;
        if (result.hasErrors()) {
            return ADD_QUESTIONNAIRE_VIEW;
        }
//        User user = new User();
//        user.setId(1);
        questionnaire.setManager(user);
        questionnaire.setQuestions(new ArrayList<Question>());
        questionnaire.setCreationDate(new Date());
        questionnaire.setActive(true);
        long id = questionnaireService.saveOrUpdate(questionnaire);
        session.setAttribute(ID_QUESTIONNAIRE_SESSION_ATTR, id);
        return "fillCreatedQuestionnaire";
//        REDIRECT_FILL_CREATEDQ;
    }


    @RequestMapping(value = "questionnaires/setInactive", method = RequestMethod.POST)
    public ModelAndView setInactive(HttpServletRequest request, HttpServletResponse response,
                                    HttpSession session) {
        User user = (User)session.getAttribute("user");
        if (user == null || !user.checkUserManager() )
            return new ModelAndView(UserController.REDIRECT_INDEX);
        ModelAndView modelAndView = new ModelAndView(REDIRECT_QUESTIONNAIRE);
        long questionnaireId = Long.parseLong(request.getParameter("questionnaireId"));
        try {
            questionnaireService.setInactive(questionnaireId);
        } catch (NotExistsException e) {
            modelAndView.addObject("errorMessage", QUESTIONNAIRE_NOT_EXISTS);
            return modelAndView;
        }
        return modelAndView;

    }


    @RequestMapping("/getQFromCategory")
    public String getQFromCategory(HttpServletRequest request, Map<String, Object> map) {

        long categoryId = Long.parseLong(request.getParameter("category_id"));
        Category category = new Category();
        category.setId(categoryId);
        try {
            map.put("questionnaireList", questionnaireService.findActiveQuestionnairesByCategory(category));
        } catch (EmptyListException e) {
            return VIEW_Q_FROM_CATEGORY;
        }

        return VIEW_Q_FROM_CATEGORY;
    }

    @RequestMapping(value = "/submitQuestionnaire")
    public String submitQuestionnaire(@ModelAttribute("questionnaire") Questionnaire questionnaire) {
        for (Question question : questionnaire.getQuestions()) {
            List<Response> responsesChecked = new ArrayList<Response>();
            for (Response response : question.getResponses()) {
                if (response.getId() != 0) {
                    responsesChecked.add(response);
                }
            }
            userResponseService.saveUserResponses(responsesChecked);
        }
        return null;
    }

    @RequestMapping(value = "/showStatistics", method = RequestMethod.GET)
    public String viewStatisticsForQuestionnaire(Map<String, Object> modelMap,
                                                 HttpServletRequest request) {

        long id = Long.parseLong(request.getParameter("questionnaireId"));
        modelMap.put("responseQStatistics", userResponseService.getStatistics(id));
        return STATISTICS_QUESTIONNAIRE_VIEW;
    }
}